<template>
    <div>
        <!-- 备忘录 -->
        <box-group-wrap pageTitle="备忘录" :isShowData="isShowData">
            <template slot="wrapBody">
                <div class="memorandum">
                    <el-table :data="memoData" style="width:100%" stripe border class="heard-bg">
                        <el-table-column label="序号" type="index" width="50"></el-table-column>
                        <el-table-column label="标题">
                            <template slot-scope="scope">
                                <div
                                    class="text_a"
                                    @click="viewMemoContent(scope.row)"
                                >{{scope.row.notesTitle}}</div>
                            </template>
                        </el-table-column>
                        <el-table-column label="提醒时间" prop="remindTime"></el-table-column>
                    </el-table>
                </div>
            </template>
            <template slot="wrapRight">
                <el-button
                    type="text"
                    size="small"
                    @click="addMemoClick"
                    icon="el-icon-circle-plus-outline"
                    style="font-size: 14px"
                >新增</el-button>
                <span class="marginmore" @click="memoMoreClick">更多>></span>
            </template>
        </box-group-wrap>
        <!--备忘录更多-->
        <el-dialog
            v-drag
            :close-on-click-modal="false"
            :visible.sync="memoMoreDialog"
            append-to-body
            center
            width="950px"
        >
            <div slot="title">备忘录管理</div>
            <el-form
                :inline="true"
                class="menu-setting demo-form-inline"
                :model="memoFormData"
                ref="memoFormData"
                size="small"
            >
                <el-form-item label="标题">
                    <el-input v-model="memoFormData.notesTitle" placeholder="请输入标题"></el-input>
                </el-form-item>
                <el-form-item label="内容">
                    <el-input v-model="memoFormData.notesContent" placeholder="请输入内容"></el-input>
                </el-form-item>
                <el-button
                    type="primary"
                    size="small"
                    icon="el-icon-search"
                    @click="hanlesearch"
                    :loading="searchLoading"
                >查 询</el-button>
                <el-button
                    type="primary"
                    size="small"
                    icon="el-icon-refresh-right"
                    @click="handleReset"
                    :loading="resetLoading"
                >重 置</el-button>
            </el-form>
            <el-table :data="memoMoreData" width="100%" stripe border class="heard-bg">
                <el-table-column label="标题" prop="notesTitle" width="180" show-overflow-tooltip></el-table-column>
                <el-table-column label="内容" prop="notesContent" width="300" show-overflow-tooltip></el-table-column>
                <el-table-column label="提醒时间" prop="remindTime"></el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button
                            type="primary"
                            icon="el-icon-edit"
                            circle
                            title="编辑"
                            @click="handleEdit(scope.row)"
                        />
                        <el-button
                            type="danger"
                            icon="el-icon-delete"
                            circle
                            title="删除"
                            @click="handleDelete(scope.row)"
                        />
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div class="pagination">
                <Pagination
                    :hanleChangeCurrentPage="hanleChangeCurrentPageMemo"
                    :handleChangeSize="handleChangeSizeMemo"
                    :currentPage="currentPageMemo"
                    :pageSize="pageSizeMemo"
                    :total="totalMemo"
                />
            </div>
        </el-dialog>
        <!--新增/编辑/查看备忘录-->
        <el-dialog
            v-drag
            :close-on-click-modal="false"
            :visible.sync="addMemoDialog"
            append-to-body
            center
            width="600px"
        >
            <div slot="title">{{ EditTitle }}</div>
            <el-form
                label-width="90px"
                class="menu-setting"
                :model="rowData"
                :rules="formRules"
                ref="memoFormData"
                size="small"
            >
                <el-form-item label="标题：" prop="notesTitle">
                    <el-input
                        v-model="rowData.notesTitle"
                        style="width: 100%"
                        :disabled="flag"
                        placeholder="请输入标题"
                    ></el-input>
                </el-form-item>
                <el-form-item label="内容：" prop="notesContent">
                    <el-input
                        type="textarea"
                        rows="5"
                        maxlength="200"
                        v-model="rowData.notesContent"
                        :disabled="flag"
                        style="width: 100%"
                        placeholder="请输入内容"
                    ></el-input>
                </el-form-item>
                <el-form-item label="提醒时间：">
                    <el-date-picker
                        :disabled="flag"
                        style="width: 100%"
                        v-model="rowData.remindTime"
                        type="datetime"
                        placeholder="请选择提醒时间"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        format="yyyy-MM-dd HH:mm:ss"
                        :picker-options="startOptions"
                    ></el-date-picker>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button
                    size="small"
                    @click="addMemoDialog = false"
                    v-if="!flag"
                    class="cancelBtn"
                >取 消</el-button>
                <el-button
                    type="primary"
                    size="small"
                    @click="submitEditMemo"
                    v-if="!flag"
                    class="submitBtn"
                    icon="el-icon-circle-check"
                >确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import moment from "moment";
import { mapGetters } from 'vuex';
// import { isEmptyObject } from '@/utils/Object';
import { getToken, getTokenHsbankNo } from '@/utils/auth';
import Pagination from '@/components/Pagination/Pagination.vue';
import BoxGroupWrap from '@/components/boxgroupwrap/BoxGroupWrap.vue';
export default {
    name: 'Memorandum',
    data() {
        return {
            memoMoreDialog: false,
            // isShowData: false,
            searchLoading: false,
            addMemoDialog: false,
            resetLoading: false,
            rowData: {
                notesTitle: '',
                notesContent: '',
                remindTime: '',
            },
            // 
            memoFormData: {
                // 备忘录查询
                notesTitle: '',
                notesContent: '',
                remindTime: '',
            },
            memoData: [],
            memoMoreData: [],
            EditTitle: '',
            // 当前页码
            currentPageMemo: 1,
            // 页码大小
            pageSizeMemo: 5,
            // 总数
            totalMemo: 0,
            flag: false,
            formRules: {
                notesTitle: [
                    { required: true, message: '请输入备忘录标题', trigger: 'blur' },
                    { max: 30, message: '字符最大长度为30', trigger: 'blur' },
                ],
                notesContent: [
                    { required: true, message: '请输入备忘录内容', trigger: 'blur' },
                    { max: 300, message: '字符最大长度为300', trigger: 'blur' },
                ],
            },
            startOptions: {
                disabledDate: (time) => {
                    return time.getTime() < new Date(moment().format('YYYY-MM-DD HH:mm:ss')).getTime();
                },
            },
            // 备忘录所有数据存储
            memoAllData: [],
            //  提示时间到数据
            // TipsDatas:{},
            outTime: '',
        }
    },
    computed: {
        ...mapGetters([
            'globalVariableNum2'
        ]),
        isShowData() {
            return this.memoData.length > 0 ? true : false;
        },
    },
    components: { 'box-group-wrap': BoxGroupWrap, Pagination },
    async mounted() {
        await this.getMemoData(1);
        console.log('this.memoData', this.memoData);
        this.outTime = this.globalVariableNum2.createTime;
        console.log('输出一下 定时器 的变量————————', this.outTime);
    },
    methods: {
        // 查看备忘录详情
        viewMemoContent(row) {
            this.EditTitle = '查看备忘录';
            this.rowData = Object.assign({}, this.memoFormData, row);
            this.addMemoDialog = true;
            this.flag = true;
            if (this.$refs.memoFormData) {
                this.$refs.memoFormData.resetFields();
            } else {
                this.$nextTick(() => {
                    // this.$refs.memoFormData.resetFields();
                });
            }
        },
        // 备忘录更多
        memoMoreClick() {
            this.memoMoreDialog = true;
            // this.getMemoData(2, this.memoFormData);
        },

        // 备忘录列表
        getInitMemoData() {
            this.memoFormData = {};
            this.getMemoData(1, this.memoFormData);
        },
        // 备忘录查询
        async getMemoData(data, form) {
            let pageNum = 1;
            let pageSize = 5;
            if (data === 1) {
                pageNum = 1;
                pageSize = 5;
            } else {
                pageNum = this.currentPageMemo;
                pageSize = this.pageSizeMemo;
            }
            let params = {
                pageNum,
                pageSize,
                agentNo: JSON.parse(getToken()).userAccount,
            };
            params = Object.assign({}, params, form);
            await this.$post.MemoMangage.searchByPage(params).then((res) => {
                if (res.data.success) {

                    // 这个是 新增备忘录
                    if (data === 1) {
                        this.memoData = res.data.content.recordList || [];
                        // console.log('memoData__有数据了', this.memoData);
                        // 备忘录数据查询
                        this.memoMoreData = res.data.content.recordList || [];
                        this.totalMemo = res.data.content.recordCount;
                    } else if (data === 2) {
                        // 这种是 修改备注 且更新 坐席页面数据
                        if (pageNum > 1) {
                            this.getMemoData(3);
                            this.memoMoreData = res.data.content.recordList || [];
                            this.totalMemo = res.data.content.recordCount;
                        } else {
                            this.memoData = res.data.content.recordList || [];
                            // console.log('memoData__有数据了', this.memoData);
                            // 备忘录数据查询
                            this.memoMoreData = res.data.content.recordList || [];
                            this.totalMemo = res.data.content.recordCount;
                        }
                    } else if (data === 3) {
                        // 这种是 修改备注 且更新 坐席页面数据
                        this.memoData = res.data.content.recordList || [];
                        // console.log('memoData__有数据了', this.memoData);
                    }
                }
            });
            // 更新 要提示的备注数据
            this.searchAlllMemoData();
        },
        hanlesearch() {
            this.getMemoData(2, this.memoFormData);
        },
        //系统进线 跑备忘录所有数据
        searchAlllMemoData() {
            let pageNum = 1;
            let pageSize = 1000000;
            let params = {
                pageNum,
                pageSize,
                agentNo: JSON.parse(getToken()).userAccount,
            }
            params = Object.assign({}, params);
            this.$post.MemoMangage.searchByPage(params).then((res) => {
                if (res.data.success) {
                    this.memoAllData = res.data.content.recordList || [];
                    // console.log('memoAllData 所有的数据了', this.memoAllData);
                    this.listeningTime();
                }
            });
        },
        // 开始过滤 过期的时间
        listeningTime() {
            if (this.memoAllData.length > 0) {
                let newTimeDate = new Date(moment()).getTime()
                let newtimelist = this.memoAllData.filter((element) => {
                    let remindTimes = new Date(element.remindTime).getTime();
                    // console.log('看看转换后的日期', remindTimes);
                    // console.log('当前的日期', newTimeDate);
                    // console.log('当前时间 + 30s', newTimeDate + 30000);
                    //  && newTimeDate < remindTimes + 30000
                    if (newTimeDate < remindTimes) {
                        console.log('走到return 当前方法结束了 ');
                        return true;
                    }
                });
                // console.log('newtimelist 没有排序的', newtimelist);
                // 给数据按照日期 时间 排序
                if (newtimelist.length > 1) {
                    newtimelist = newtimelist.sort(function (item1, item2) {
                        let valTime1 = new Date(item1.remindTime).getTime();
                        let valTime2 = new Date(item2.remindTime).getTime();
                        if (valTime1 < valTime2) {
                            return -1;
                        } else if (valTime1 > valTime2) {
                            return 1;
                        } else {
                            return 0;
                        }
                    })
                } else if (newtimelist.length === 0) {
                    // 开始 监听之前 清除上一次的监听
                    // console.log('检查上次的定时器是否被清除333 ———— 同时 方法结束了', this.outTime);
                    clearInterval(this.outTime);
                    return false;
                }
                // console.log('newtimelist排序后的————————', newtimelist);
                this.memoAllData = newtimelist;
                // 开始 监听之前 清除上一次的监听
                // console.log('检查是否有定时器——————', this.outTime);
                clearInterval(this.outTime);
                // console.log('检查上次的定时器是否被清除222', this.outTime);
                // 开始监听 
                // console.log('监听时间问题', newtimelist[0]);
                this.listeningOneDateFun(newtimelist[0])
                // for (let index = 0; index < newtimelist.length; index++) {
                //     const element = array[index];
                //      this.listeningOneDateFun(newtimelist[index])
                //     console.log('123455677889');
                // }
            }
        },
        // 开始监听所有的 数据的时间
        listeningOneDateFun(timeObj) {
            let paramTime = new Date(timeObj.remindTime).getTime();
            let currnetTime;
            this.outTime = setInterval(() => {
                currnetTime = new Date().getTime();
                // console.log('打印当前时间', moment(currnetTime).format('YYYY-MM-DD HH:mm:ss'));
                // console.log('打印要监听的时间', moment(paramTime).format('YYYY-MM-DD HH:mm:ss'));
                // console.log('输出当前的定时器 判断是否相同__', this.outTime);
                if (paramTime <= currnetTime) {
                    // this.TipsDatas = timeObj
                    // console.log('打印出要提示的数据', timeObj);
                    const h = this.$createElement;
                    this.$notify({
                        title: '备忘录提醒:' + timeObj.notesTitle,
                        message: h('i', { style: 'color:teal' }, timeObj.notesContent),
                        duration: 0
                    });
                    // 清除定时器
                    clearInterval(this.outTime);
                    // console.log('检查上次的定时器是否被清除', this.outTime);
                    // 开启下个监听
                    this.listeningTime();
                }
            }, 30000);
            // console.log('this.outTime__定时器', this.outTime);
            let objs = this.globalVariableNum2;
            console.log('objs', objs);
            objs.createTime = this.outTime;
            // console.log('输出要存到缓存里的数据——————————————————————', objs);
            this.$store.dispatch('menu/updatedGlobalVariableNum2', objs)
        },

        // 备忘录重置
        handleReset() {
            this.memoFormData = {
                notesTitle: '',
                notesContent: '',
                remindTime: '',
            };
            this.getMemoData(2, this.memoFormData);
        },
        // 添加备忘录
        addMemoClick() {
            this.EditTitle = '新增备忘录';
            this.rowData = Object.assign({}, this.memoFormData);
            this.addMemoDialog = true;
            this.flag = false;
            // 解决一进来就进行表单验证问题
            if (this.$refs.memoFormData) {
                this.$refs.memoFormData.resetFields();
            } else {
                this.$nextTick(() => {
                    // this.$refs.memoFormData.resetFields();
                });
            }
        },
        // 编辑备忘录
        handleEdit(row) {
            this.EditTitle = '编辑备忘录';
            this.rowData = Object.assign({}, this.memoFormData, row);
            this.addMemoDialog = true;
            this.flag = false;
            if (this.$refs.memoFormData) {
                this.$refs.memoFormData.resetFields();
            } else {
                this.$nextTick(() => {
                    // this.$refs.memoFormData.resetFields();
                });
            }
        },
        // 添加编辑备忘录确定
        submitEditMemo() {
            if (this.rowData.id) {
                // 编辑
                this.$refs.memoFormData.validate((valid) => {
                    if (valid) {
                        this.$post.MemoMangage.updateNotes(this.rowData).then((res) => {
                            if (res.data.success) {
                                this.$message.success('修改成功！');
                                this.getMemoData(2, this.memoFormData);
                                this.addMemoDialog = false;
                                this.flag = false;
                            } else {
                                this.$message.error(res.data.msg);
                            }
                        });
                    } else {
                        this.$message.warning('请完成表单填写！');
                    }
                });
            } else {
                // 添加
                this.$refs.memoFormData.validate((valid) => {
                    if (valid) {
                        this.$post.MemoMangage.addNotes(this.rowData).then((res) => {
                            if (res.data.success) {
                                this.$message.success('添加成功！');
                                this.getInitMemoData();
                                this.addMemoDialog = false;
                                this.flag = false;
                            } else {
                                this.$message.error(res.data.msg);
                            }
                        });
                    } else {
                        this.$message.warning('请完成表单填写！');
                    }
                });
            }
        },
        // 删除备忘录
        handleDelete(row) {
            this.$confirm('确认删除该备忘录？', '提示', { customClass: 'warning', type: 'warning' })
                .then(() => {
                    this.$post.MemoMangage.deleteNotes({ id: row.id }).then((res) => {
                        if (res.data.success) {
                            this.$message.success('删除成功！');
                            if (this.memoMoreData.length === 1) {
                                this.currentPageMemo = this.currentPageMemo - 1;
                            }
                            this.getMemoData(2, this.memoFormData);
                            // this.getInitMemoData();
                        } else {
                            this.$message.error(res.data.msg);
                        }
                    });
                })
                .catch(() => { });
        },
        // 页码切换方法
        hanleChangeCurrentPageMemo(val) {
            this.currentPageMemo = val;
            this.getMemoData(2, this.memoFormData);
        },
        // 切换分页大小方法
        handleChangeSizeMemo(val) {
            this.pageSizeMemo = val;
            this.getMemoData(2, this.memoFormData);
        },
    },
}
</script>

<style scoped lang="scss">
.marginmore {
    margin-left: 15px;
}
</style>
<style lang="scss">
.el-notification.right {
    .el-notification__group {
        .el-notification__title {
            font-size: 14px;
            color: #03a9f4;
        }
    }
}
</style>